package com.eqdd.yiqidian.ui;

import android.content.Intent;
import android.databinding.DataBindingUtil;

import com.eqdd.yiqidian.IndicatorItemCustom;
import com.eqdd.yiqidian.R;
import com.eqdd.yiqidian.adapter.recycleadapter.BaseQuickAdapter;
import com.eqdd.yiqidian.adapter.recycleadapter.BaseViewHolder;
import com.eqdd.yiqidian.adapter.recycleadapter.ItemClickSupport;
import com.eqdd.yiqidian.base.BaseActivity;
import com.eqdd.yiqidian.AreaActivityCustom;
import com.eqdd.yiqidian.base.Config;
import com.eqdd.yiqidian.bean.AreaBean;
import com.eqdd.yiqidian.http.HttpConfig;
import com.eqdd.yiqidian.http.HttpPresneter;
import com.eqdd.yiqidian.listener.OnMyClickListener;
import com.eqdd.yiqidian.utils.ToastUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import rx.Observable;
import rx.functions.Func1;

public class AreaActivity extends BaseActivity {
    private AreaActivityCustom dataBinding;
    private List<String> areaNames = new ArrayList<>();
    private Map<Integer, Integer> deeps = new HashMap<>();
    private List<AreaBean> areaBean;
    private BaseQuickAdapter<AreaBean, BaseViewHolder> quickAdapter;
    private int deep;
    private int nowdeep;
    private String result;

    @Override
    public void initBinding() {
        dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_area);
        initTopTitleBar(View.VISIBLE, "地区");
        initTopRightText("确定", v -> {
            if (!TextUtils.isEmpty(result)) {
                Intent intent = new Intent();
                intent.putExtra(Config.AREA_CONTENT, result);
                setResult(Config.SUCCESS, intent);
                finish();
            } else {
                ToastUtil.showLong("你还没选地区呢");
            }
        });
    }

    @Override
    public void initData() {
        deep = 3;
        nowdeep = 1;
        Observable.just(1)
                .flatMap(new Func1<Integer, Observable<String>>() {
                    @Override
                    public Observable<String> call(Integer integer) {
                        return new HttpPresneter.Builder<String>(HttpConfig.AREA_OPTIONS, String.class, null)
                                .build()
                                .getObserverBean();
                    }
                })
                .flatMap(new Func1<String, Observable<String>>() {
                    @Override
                    public Observable<String> call(String integer) {

                        String msg = null;
                        try {
                            msg = new JSONObject(integer).getString("msg");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        String url = HttpConfig.BASE_URL_NO + msg;
                        return new HttpPresneter.Builder<String>(url, String.class, null)
                                .build()
                                .getObserverBean();
                    }
                })
                .subscribe((s) -> {
                    areaBean = new Gson().fromJson(s, new TypeToken<List<AreaBean>>() {
                    }.getType());
                    areaNames.add("请选择");
                    initRoot(areaBean);
                });
    }

    @Override
    public void setView() {

    }

    private void initRoot(List<AreaBean> areaBeanList) {
        ArrayList<AreaBean> tempAreaBeans = new ArrayList<>();
        tempAreaBeans.addAll(areaBeanList);
        dataBinding.llRoot.removeAllViews();
        for (int i = 0; i < areaNames.size(); i++) {
            IndicatorItemCustom inflate = DataBindingUtil.inflate(getLayoutInflater(), R.layout.item_indicator, dataBinding.llRoot, false);
            LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) inflate.getRoot().getLayoutParams();
            layoutParams.weight = 1;
            layoutParams.width = 0;
            inflate.tvTitle.setText(areaNames.get(i));
            inflate.getRoot().setLayoutParams(layoutParams);
            inflate.getRoot().setOnClickListener(new OnMyClickListener(i) {
                @Override
                public void onClick(View v) {
                    if (getPosition() == nowdeep - 1) {
                        return;
                    } else {
                        result = "";
                        int len = areaNames.size() - 1;
                        for (int j = len - 1; j >= getPosition(); j--) {
                            areaNames.remove(j + 1);
                        }
                        nowdeep = getPosition() + 1;
                        initRoot(getAreaBean(getPosition()));
                    }
                }
            });
            dataBinding.llRoot.addView(inflate.getRoot());
        }
        if (quickAdapter == null) {
            quickAdapter = new BaseQuickAdapter<AreaBean, BaseViewHolder>(R.layout.list_item_area, new ArrayList<AreaBean>()) {

                @Override
                protected void convert(BaseViewHolder helper, AreaBean item) {
                    helper.setText(R.id.textView, item.getName());
                }
            };
            dataBinding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
            dataBinding.recyclerView.setAdapter(quickAdapter);
            ItemClickSupport.addTo(dataBinding.recyclerView)
                    .setOnItemClickListener((rv, p, v) -> {
                        if (nowdeep < deep) {
                            result = "";
                            deeps.put(nowdeep, p);
                            nowdeep++;
                            areaNames.set(areaNames.size() - 1, quickAdapter.getItem(p).getName());
                            areaNames.add("请选择");
                            initRoot(quickAdapter.getData().get(p).getSub());
                        } else {
                            deeps.put(nowdeep, p);
                            areaNames.set(deep - 1, quickAdapter.getItem(p).getName());
                            result = getAreaName();
                            initRoot(quickAdapter.getData());
                        }
                    });
        }
        quickAdapter.notifyDataChanged(tempAreaBeans, true);

    }

    private String getAreaName() {
        String s = "";
        for (String s1 : areaNames) {
            s += s1;
        }
        return s;
    }

    private List<AreaBean> getAreaBean(int position) {
        List<AreaBean> temp = areaBean;
        for (int i = 0; i < position; i++) {
            temp = temp.get(deeps.get(i + 1)).getSub();
        }
        return temp;
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {

        }
    }
}
